<?php
require_once '../data/data.php';

// 开启session
session_start();

// 只支持POST请求，否则返回405错误
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
   header('HTTP/1.1 405 Method Not Allowed');
   return;
}

$token = isset($_POST['csrf_token']) ? $_POST['csrf_token'] : '';
if (trim($token) == '' || $_SESSION['csrf-token'] != $token) {
   echo '令牌错误';
   return;
}
// $_SESSION['csrf-token'] = md5(mt_rand() . time());

// 获取请求中的用户输入数据
$userName = isset($_POST['username']) ? htmlspecialchars($_POST['username']) : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$passwordConfirm = isset($_POST['password_confirm']) ? $_POST['password_confirm'] : '';

// 数据验证，以及两次输入的密码是否一致
$hasError = false;
$inputBag = [
   'username' => ''
];
$errorBag = [
   'username' => '',
   'password' => '',
   'password_confirm' => ''
];
if (trim($userName) == '') {
   $hasError = true;
   $errorBag['username'] = '用户名不能为空';
}
if (strlen($password) < 6) {
   $hasError = true;
   $errorBag['password'] = '密码长度必须大于等于6位';
}
if ($password !== $passwordConfirm) {
   $hasError = true;
   $errorBag['password_confirm'] = '两次输入的密码必须一致'; 
}
// 验证用户名是否已经被注册
$sql = 'select id from users where user_name=?';
$data = query($sql, [$userName]);
if (count($data) > 0) {
    $hasError = true;
    $errorBag['username'] = '该用户名已被注册';
}

// 如果数据验证出现错误，则把错误包数据存入session，重定向到表单页面
$inputBag['username'] = $userName;
$_SESSION['has_error'] = $hasError;
$_SESSION['input_bag'] = $inputBag;
$_SESSION['error_bag'] = $errorBag;
if ($hasError === true) {
   // 重定向
   header('Location:../register.php');
   return;
}

// 验证通过，写入数据库
$password = password_hash($password, PASSWORD_BCRYPT);
$sql = 'insert into users(user_name,password,register_time) values(?,?,now())';
$args = [$userName, $password];
if (execute($sql, $args)) {
   header('Location:../signin.php');
} else {
   header('Location:../register.php');
}
